<template>
	<view class="cu-form-group">
		<view class="grid col-4 grid-square flex-sub">
			<view class="bg-img flex" v-for="(path,index) in imgTempPaths" :key="index" @tap="previewImg(imgTempPaths,index)"
			 :data-url="path">
				<image :src="path" mode="aspectFill"   class="bg-img only-img"></image>
				<view v-if="!disabled" class="cu-tag bg-red" @tap.stop="deleteImage" :data-index="index">
					<text class='cuIcon-close'></text>
				</view>
			</view>
			<view class="solids flex" @tap="selectImage" v-if="disabled ? false : imgTempPaths.length<count">
				<text class='cuIcon-cameraadd' ></text>
			</view>
		</view>
	</view>
</template>



<script>
	// import {
	// 	getQueryString
	// } from "@/utils/util.js";
	import {
		domain
	} from '../config';
	import {
		uploadFile
	} from '@/utils/request.js';
	export default {
		name: 'image-upload',
		props: {
			serverUrl: {
				type: String,
				default: '',
			},
			header: Object,
			fileKeyName: String,
			count: [String, Number],
			disabled: [String, Boolean],
			defaultFile:Array
		},
		data() {
			return {
				imgTempPaths: [],
				uploadFiles:[]
			}
		},
		watch: {
			defaultFile: {
				//hander监听方法
				handler(newValue) {
					this.imgTempPaths = newValue;
				},
				deep: true, //深度监听
				// immediate: true
			}
		},
		methods: {
			//预览图片
			previewImg(imgTempPath, current) {
				uni.previewImage({
					urls: imgTempPath,
					current: current
				})
			},
			selectImage: function() {
				uni.chooseImage({
					count: this.count, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (e) => {
						uni.showLoading({
							title: "正在上传..."
						})
						//定义数据接收图片临时路径
						let imagePathArr = e.tempFilePaths
						//默认上传文件名为file
						let keyname = (this.fileKeyName ? this.fileKeyName : 'file');
						for (let i = 0; i < imagePathArr.length; i++) {
							let params = {
								filePath: imagePathArr[i],
								method: 'POST',
								name: keyname,
								url:'/uni/UploadFeedbackfile'
							}
							uploadFile({
								...params
							}).then((path) => {
								if (!path) return;
								console.log('path&&&&------',path)
								 let _res=JSON.stringify(path)
								 let res=JSON.parse(_res)
								
								console.log('path&&&&------',typeof(path),res)
								this.imgTempPaths.push(imagePathArr[i]);
								this.uploadFiles = [...this.uploadFiles,path];
								this.$emit('getFile', {files:this.uploadFiles,wxFiles:this.imgTempPaths});
							})
						}
					},
					complete() {
						uni.hideLoading()
					}
				})
				

			},
			deleteImage: function(e) {
				const imageIndex = e.currentTarget.dataset.index;
				this.imgTempPaths.splice(imageIndex, 1);
				this.uploadFiles.splice(imageIndex, 1);
				this.$emit('getFile', {files:this.uploadFiles,wxFiles:this.imgTempPaths});
			}
		}
	}
</script>
<style>
	.cu-form-group {
		padding-top: 10px;
		background: transparent;
	}
</style>
